var dbConfig = require("../utils/dbconfig");
var express = require("express");
var Response = require("../utils/response");
const { query } = require("express");

function searchPerson(req, res, next) {
  let obj = {
    realname: "".concat("%", req.query.realname ? req.query.realname : "", "%"),
    username: "".concat("%", req.query.username ? req.query.username : "", "%"),
    gender: "".concat(req.query.gender ? req.query.gender : ""),
    status: "".concat(req.query.status ? req.query.status : ""),
    rank: "".concat(req.query.rank ? req.query.rank : ""),
    position_no: "".concat(req.query.position_no ? req.query.position_no : ""),
    department_id: "".concat(req.query.department_id ? req.query.department_id : ""),
  };
  let str = `select * from base_user where `;
  const keys = Object.keys(obj);
  let i = 0;
  for (let [index, item] of keys.entries()) {
    const val = obj[item];
    if (val != "" && item.length != 8) {
      i++;
      if (i > 1) {
        str += " and " + "`" + item + "`" + "=" + "'" + val + "'";
      } else {
        str += " " + "`" + item + "`" + "=" + "'" + val + "'";
      }
    } else if (val != "") {
      i++;
      if (i > 1) {
        str += " and " + item + " like " + "'" + val + "'";
      } else {
        str += " " + item + " like " + "'" + val + "'";
      }
    }
  }
  let sql = str;
  // let sql = `select * from base_user where realname like "${obj.realname}" and username like "${obj.username}" and gender like "${obj.gender}" and 'status' like "${obj.status}" and 'rank' like "${obj.rank}" and position_no like "${obj.position}" and department_id like "${obj.department}" `;
  let sqlArr = [];
  var callBack = (err, data) => {
    if (err) {
      console.log("连接出错了", err);
    } else {
      if (data.length > 0) {
        res.send(new Response(200, "查询成功", data));
        console.log(sql);
      } else {
        res.send(new Response(500, "查询失败", data));
      }
    }
  };
  dbConfig.sqlConnection(sql, sqlArr, callBack);
}

module.exports = {
  searchPerson,
};
